import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14
import QtCharts 2.3

Item {
    id: dataVisualizationPage
    
    property var dataVis
    property var deviceCtrl
    property var samplingMgr
    property var qmlBridge
    
    Rectangle {
        anchors.fill: parent
        color: "#f5f5f5"
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            // Header
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 60
                color: "#FF5722"
                radius: 8
                
                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 20
                    
                    Text {
                        text: "Data Visualization & Analytics"
                        font.pixelSize: 20
                        font.bold: true
                        color: "white"
                    }
                    
                    Item { Layout.fillWidth: true }
                    
                    ComboBox {
                        id: timeRangeCombo
                        model: ["Last Hour", "Last 6 Hours", "Last 24 Hours", "Last Week"]
                        currentIndex: 1
                        onCurrentTextChanged: updateCharts()
                    }
                    
                    Button {
                        text: "Export Data"
                        onClicked: {
                            if (dataVis) {
                                dataVis.exportData()
                                console.log("Data export requested")
                            }
                        }
                    }
                }
            }
            
            // Charts Grid
            GridLayout {
                Layout.fillWidth: true
                Layout.fillHeight: true
                columns: 2
                columnSpacing: 20
                rowSpacing: 20
                
                // Flow Rate Chart
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 15
                        spacing: 10
                        
                        Text {
                            text: "Flow Rate Trend"
                            font.pixelSize: 16
                            font.bold: true
                            color: "#333"
                        }
                        
                        ChartView {
                            id: flowRateChart
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            antialiasing: true
                            backgroundColor: "transparent"
                            legend.visible: false
                            
                            LineSeries {
                                id: flowRateSeries
                                name: "Flow Rate"
                                color: "#2196F3"
                                width: 3
                                
                                axisX: DateTimeAxis {
                                    id: flowRateAxisX
                                    format: "hh:mm"
                                    tickCount: 6
                                }
                                
                                axisY: ValueAxis {
                                    id: flowRateAxisY
                                    min: 0
                                    max: 20
                                    tickCount: 5
                                    labelFormat: "%.1f L/min"
                                }
                            }
                        }
                    }
                }
                
                // Temperature & Humidity Chart
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 15
                        spacing: 10
                        
                        Text {
                            text: "Environmental Conditions"
                            font.pixelSize: 16
                            font.bold: true
                            color: "#333"
                        }
                        
                        ChartView {
                            id: environmentChart
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            antialiasing: true
                            backgroundColor: "transparent"
                            
                            LineSeries {
                                id: temperatureSeries
                                name: "Temperature (°C)"
                                color: "#FF5722"
                                width: 3
                                
                                axisX: DateTimeAxis {
                                    id: envAxisX
                                    format: "hh:mm"
                                    tickCount: 6
                                }
                                
                                axisY: ValueAxis {
                                    id: tempAxisY
                                    min: 15
                                    max: 35
                                    tickCount: 5
                                    labelFormat: "%.1f°C"
                                }
                            }
                            
                            LineSeries {
                                id: humiditySeries
                                name: "Humidity (%)"
                                color: "#009688"
                                width: 3
                                
                                axisX: envAxisX
                                axisYRight: ValueAxis {
                                    id: humidityAxisY
                                    min: 30
                                    max: 80
                                    tickCount: 5
                                    labelFormat: "%.1f%"
                                }
                            }
                        }
                    }
                }
                
                // Sampling Statistics
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 15
                        spacing: 10
                        
                        Text {
                            text: "Sampling Statistics"
                            font.pixelSize: 16
                            font.bold: true
                            color: "#333"
                        }
                        
                        ChartView {
                            id: samplingChart
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            antialiasing: true
                            backgroundColor: "transparent"
                            
                            PieSeries {
                                id: samplingPieSeries
                                
                                PieSlice {
                                    label: "Completed"
                                    value: 15
                                    color: "#4CAF50"
                                }
                                PieSlice {
                                    label: "Running"
                                    value: 2
                                    color: "#FF9800"
                                }
                                PieSlice {
                                    label: "Pending"
                                    value: 5
                                    color: "#2196F3"
                                }
                                PieSlice {
                                    label: "Failed"
                                    value: 1
                                    color: "#F44336"
                                }
                            }
                        }
                    }
                }
                
                // System Performance
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 15
                        spacing: 10
                        
                        Text {
                            text: "System Performance"
                            font.pixelSize: 16
                            font.bold: true
                            color: "#333"
                        }
                        
                        GridLayout {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            columns: 2
                            columnSpacing: 20
                            rowSpacing: 15
                            
                            // Battery Level Gauge
                            Column {
                                Layout.fillWidth: true
                                spacing: 10
                                
                                Text {
                                    text: "Battery Level"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#666"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }
                                
                                Rectangle {
                                    width: 120
                                    height: 120
                                    color: "transparent"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                    
                                    Canvas {
                                        id: batteryGauge
                                        anchors.fill: parent
                                        
                                        property real batteryLevel: deviceCtrl ? deviceCtrl.batteryLevel : 75
                                        
                                        onPaint: {
                                            var ctx = getContext("2d")
                                            ctx.clearRect(0, 0, width, height)
                                            
                                            var centerX = width / 2
                                            var centerY = height / 2
                                            var radius = Math.min(width, height) / 2 - 10
                                            
                                            // Background circle
                                            ctx.beginPath()
                                            ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
                                            ctx.strokeStyle = "#e0e0e0"
                                            ctx.lineWidth = 8
                                            ctx.stroke()
                                            
                                            // Battery level arc
                                            var startAngle = -Math.PI / 2
                                            var endAngle = startAngle + (batteryLevel / 100) * 2 * Math.PI
                                            
                                            ctx.beginPath()
                                            ctx.arc(centerX, centerY, radius, startAngle, endAngle)
                                            ctx.strokeStyle = batteryLevel > 20 ? "#4CAF50" : "#F44336"
                                            ctx.lineWidth = 8
                                            ctx.stroke()
                                            
                                            // Center text
                                            ctx.fillStyle = "#333"
                                            ctx.font = "16px Arial"
                                            ctx.textAlign = "center"
                                            ctx.fillText(batteryLevel.toFixed(0) + "%", centerX, centerY + 5)
                                        }
                                        
                                        Timer {
                                            interval: 1000
                                            running: true
                                            repeat: true
                                            onTriggered: batteryGauge.requestPaint()
                                        }
                                    }
                                }
                            }
                            
                            // System Status
                            Column {
                                Layout.fillWidth: true
                                spacing: 15
                                
                                Text {
                                    text: "System Status"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#666"
                                }
                                
                                Column {
                                    spacing: 8
                                    
                                    Row {
                                        spacing: 10
                                        
                                        Rectangle {
                                            width: 12
                                            height: 12
                                            radius: 6
                                            color: "#4CAF50"
                                        }
                                        
                                        Text {
                                            text: "Device Online"
                                            font.pixelSize: 12
                                            color: "#333"
                                        }
                                    }
                                    
                                    Row {
                                        spacing: 10
                                        
                                        Rectangle {
                                            width: 12
                                            height: 12
                                            radius: 6
                                            color: "#4CAF50"
                                        }
                                        
                                        Text {
                                            text: "Database Connected"
                                            font.pixelSize: 12
                                            color: "#333"
                                        }
                                    }
                                    
                                    Row {
                                        spacing: 10
                                        
                                        Rectangle {
                                            width: 12
                                            height: 12
                                            radius: 6
                                            color: deviceCtrl && deviceCtrl.deviceStatus === 0 ? "#4CAF50" : "#FF9800"
                                        }
                                        
                                        Text {
                                            text: "Sampling Ready"
                                            font.pixelSize: 12
                                            color: "#333"
                                        }
                                    }
                                    
                                    Row {
                                        spacing: 10
                                        
                                        Rectangle {
                                            width: 12
                                            height: 12
                                            radius: 6
                                            color: "#4CAF50"
                                        }
                                        
                                        Text {
                                            text: "Audit Logging Active"
                                            font.pixelSize: 12
                                            color: "#333"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Data update timer
    Timer {
        id: dataUpdateTimer
        interval: 5000 // Update every 5 seconds
        running: true
        repeat: true
        onTriggered: updateChartData()
    }
    
    Component.onCompleted: {
        initializeCharts()
    }
    
    function initializeCharts() {
        // Initialize flow rate chart with sample data
        var now = new Date()
        for (var i = 0; i < 20; i++) {
            var time = new Date(now.getTime() - (20 - i) * 60000) // 1 minute intervals
            var flowRate = 8 + Math.random() * 4 // Random flow rate between 8-12
            flowRateSeries.append(time.getTime(), flowRate)
        }
        
        // Initialize environment chart with sample data
        for (var j = 0; j < 20; j++) {
            var time2 = new Date(now.getTime() - (20 - j) * 60000)
            var temp = 22 + Math.random() * 6 // Temperature 22-28°C
            var humidity = 45 + Math.random() * 20 // Humidity 45-65%
            temperatureSeries.append(time2.getTime(), temp)
            humiditySeries.append(time2.getTime(), humidity)
        }
        
        updateCharts()
    }
    
    function updateCharts() {
        console.log("Updating charts for time range:", timeRangeCombo.currentText)
        // In real implementation, this would fetch data based on selected time range
    }
    
    function updateChartData() {
        if (deviceCtrl) {
            // Add new data point to flow rate chart
            var now = new Date()
            flowRateSeries.append(now.getTime(), deviceCtrl.flowRate)
            
            // Remove old data points (keep last 20)
            while (flowRateSeries.count > 20) {
                flowRateSeries.remove(0)
            }
            
            // Add new data to environment chart
            temperatureSeries.append(now.getTime(), deviceCtrl.temperature)
            humiditySeries.append(now.getTime(), deviceCtrl.humidity)
            
            // Remove old data points
            while (temperatureSeries.count > 20) {
                temperatureSeries.remove(0)
            }
            while (humiditySeries.count > 20) {
                humiditySeries.remove(0)
            }
        }
    }
}